package com.audaque.springboot.foshanupload.security.filter;

/**
 * @author zgb
 * @desc ...
 * @date 2023-07-13 20:48:42
 */


import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import com.audaque.springboot.foshanupload.jwtcore.component.iface.JwtProviderIface;
import com.audaque.springboot.foshanupload.jwtvalid.component.JwtLoginProvider;
import com.audaque.springboot.foshanupload.jwtvalid.filter.JwtBodyFilter;
import com.audaque.springboot.foshanupload.security.service.impl.MyUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zgb
 * @desc 自定义jwt认证过滤器
 * @date 2022-08-05 17:44:42
 */

@Slf4j
public class MyJwtAuthenticationFilter extends OncePerRequestFilter {
  @Autowired
  private JwtProviderIface jwtProviderIface;


  @Autowired
  private MyUserDetailService myUserDetailService;

  @Autowired
  private FilterRegistrationBean jwtBodyFilterRegistration;
  @Autowired
  private JwtLoginProvider jwtLoginProvider;


  @Override
  public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
	JwtBodyFilter jwtBodyFilter = (JwtBodyFilter) jwtBodyFilterRegistration.getFilter();
	String[] excludedUris = jwtBodyFilter.getExcludedUris();
	//jwt登录
	jwtLoginProvider.login(request, response);
	TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = TransmittableThreadLocalCurrentUser.getCurrentUser();
	if (transmittableThreadLocalCurrentUser != null) {
	  String username = transmittableThreadLocalCurrentUser.getUsername();
	  UsernamePasswordAuthenticationToken usernamePasswordAuthenticationTokenByByUsername = myUserDetailService.getUsernamePasswordAuthenticationTokenByByUsername(username);
	  //将认证信息存到安全上下文中
	  SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationTokenByByUsername);
	}

	chain.doFilter(request, response);
	return;
  }

}
